package com.example.composableexample.pager.image

import androidx.compose.foundation.Image
import androidx.compose.foundation.gestures.*
import androidx.compose.foundation.layout.*
import androidx.compose.material.Surface
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.google.accompanist.pager.*
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.flow.collect
import kotlin.math.absoluteValue

data class Image(val url: String)

@Preview
@Composable
fun ImageBrowserScreenPreview() {
    val images = listOf(
        Image("https://img-blog.csdnimg.cn/bc272578b5124b409a67dc3a27b2f31d.png"),
        Image("https://img-blog.csdnimg.cn/535949162c6346fc89ed40550580de2d.png"),
        Image("https://img-blog.csdnimg.cn/d07c9e9b9dd049e4ac837d7e6bc66f90.png"),
        Image("https://img-blog.csdnimg.cn/9a2c8845a9eb473d9f69ae5edb1719c4.png"),
    )

    ImageBrowserScreen(images, selectImage = images[0])
}


/**
 * 大图预览
 */
@OptIn(ExperimentalPagerApi::class)
@Composable
fun ImageBrowserScreen(images: List<Image>, selectImage: Image) {

    var currentIndex = 0

    images.forEachIndexed { index, image ->
        if (image.url == selectImage.url) {
            currentIndex = index
            return@forEachIndexed
        }
    }
    /**
     * 界面状态变更
     */
    val pageState = rememberPagerState(initialPage = currentIndex)

    Box {
        HorizontalPager(
            count = images.size,
            state = pageState,
            contentPadding = PaddingValues(horizontal = 0.dp),
            modifier = Modifier.fillMaxSize()
        ) { page ->
            println("ImageBrowserItem current page: $page")
            ImageBrowserItem(images[page], page, this)
        }

        HorizontalPagerIndicator(
            pagerState = pageState,
            activeColor = Color.White,
            inactiveColor = MaterialTheme.colorScheme.onBackground,
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(60.dp)
        )

        LaunchedEffect(pageState) {
            snapshotFlow { pageState }.collect { pageState ->
                println("ImageBrowserItem LaunchedEffect pageState currentPageOffset: $pageState.currentPageOffset")
            }
        }
    }
}

@OptIn(ExperimentalPagerApi::class)
@Composable
fun ImageBrowserItem(image: Image, page: Int = 0,  pagerScope: PagerScope) {
    /**
     * 缩放比例
     */
    var scale by remember { mutableStateOf(1f) }

    /**
     * 偏移量
     */
    var offset  by remember { mutableStateOf(Offset.Zero) }

    /**
     * 监听手势状态变换
     */
    var state =
        rememberTransformableState(onTransformation = { zoomChange, panChange, rotationChange ->
            scale = (zoomChange * scale).coerceAtLeast(1f)
            scale = if (scale > 5f) {
                5f
            } else {
                scale
            }
            println("ImageBrowserItem detectTapGestures rememberTransformableState scale: $scale")
        })

    Surface(
//        modifier = Modifier
//            .fillMaxSize(),
        color = Color.Black,
    ) {
        AsyncImage(
            model = image.url,
            contentDescription = "",
            contentScale = ContentScale.FillWidth,
            modifier = Modifier
                .fillMaxSize()
                .transformable(state = state)
                .graphicsLayer {  //布局缩放、旋转、移动变换
                    scaleX = scale
                    scaleY = scale
                    translationX = offset.x
                    translationY = offset.y
                    val pageOffset =
                        pagerScope.calculateCurrentOffsetForPage(page = page).absoluteValue
                    if (pageOffset == 1.0f) {
                        scale = 1.0f
                    }
                    println("ImageBrowserItem pagerScope calculateCurrentOffsetForPage pageOffset: $pageOffset")
                }
                .pointerInput(Unit) {
                    detectTapGestures(
                        onDoubleTap = {
                            println("ImageBrowserItem detectTapGestures onDoubleTap offset: $it")
                            scale = if (scale <= 1f) {
                                2f
                            } else {
                                1f
                            }
                            offset = Offset.Zero
                        },
                        onTap = {

                        }
                    )
                }
        )
    }
}


